<template>
  <div :class="{'only-view-mode': !isEdit}" class="common-project-container">
    <SectionTitle title="报销项目" style="margin: 32px 0 16px;">
      <el-tooltip placement="top">
        <div slot="content">{{ titleTip }}</div>
        <tipIcon is-diy/>
      </el-tooltip>
      <div class="total-amount-price">
        <img :src="AmountIcon">总报销金额：
        <span class="price">{{ getTotalReimbursementAmount }}</span>
      </div>
      <div v-if="isEdit" class="options-btn-group">
        <PlainCreateBtn @click="handleAdd">添加</PlainCreateBtn>
      </div>
    </SectionTitle>
    <el-table
      :data="travelProjectList"
      header-cell-class-name="dynamic-edit-table-cell"
      class="fb-table"
      empty-text="暂无数据"
      fit
    >
      <el-table-column prop="departure" width="150">
        <template slot="header" slot-scope="scope">
          <div class="dynamic-table-header">
            <span v-if="isEdit" style="color: #f56c6c;">*</span>
            <span class="label">出发地</span>
          </div>
        </template>
        <template slot-scope="scope">
          <div v-if="isEdit" :class="{ 'isError': errorCell.includes(`departure${scope.$index}`) }">
            <ThreeLevelArea
              v-if="isEdit"
              :selected-options="onSelectArea(scope.row['departure'])"
              separator="-"
              select-type="city"
              placeholder="请选择"
              @update:options="threeLevelArea($event, scope.row, 'departure')"
            />
          </div>
          <ToolTip v-else :content="scope.row.departure" />
        </template>
      </el-table-column>
      <el-table-column prop="arrival" width="150">
        <template slot="header" slot-scope="scope">
          <div class="dynamic-table-header">
            <span v-if="isEdit" style="color: #f56c6c;">*</span>
            <span class="label">目的地</span>
          </div>
        </template>
        <template slot-scope="scope">
          <div v-if="isEdit" :class="{ 'isError': errorCell.includes(`arrival${scope.$index}`) }">
            <ThreeLevelArea
              :selected-options="onSelectArea(scope.row['arrival'])"
              separator="-"
              select-type="city"
              placeholder="请选择"
              @update:options="threeLevelArea($event, scope.row, 'arrival')"
            />
          </div>
          <ToolTip v-else :content="scope.row.arrival || '内蒙古自治区-锡林郭勒盟'" />
        </template>
      </el-table-column>
      <el-table-column prop="dateRangeData" width="300">
        <template slot="header" slot-scope="scope">
          <div class="dynamic-table-header">
            <span v-if="isEdit" style="color: #f56c6c;">*</span>
            <span class="label">起止时间</span>
          </div>
        </template>
        <template slot-scope="scope">
          <div v-if="isEdit" :class="{ 'isError': errorCell.includes(`dateRangeData${scope.$index}`) }">
            <el-date-picker
              v-model="scope.row['dateRangeData']"
              :editable="false"
              :default-time="['09:00:00', '18:00:00']"
              clearable
              append-to-body
              type="datetimerange"
              format="yyyy/MM/dd a"
              placeholder="请选择"
              start-placeholder="开始时间"
              range-separator="至"
              end-placeholder="结束时间"
              value-format="timestamp"
              size="small"
              style="padding-right: 0"
              @change="datePickerChange(scope.row['dateRangeData'], scope.$index)" />
          </div>
          <div v-else style="display:flex;align-items:center;">
            <span>{{ scope.row['dateRangeData'] && scope.row['dateRangeData'][0] | format('YYYY/MM/DD a') }}</span>
            <span style="margin: 0 8px"> 至 </span>
            <span>{{ scope.row['dateRangeData'] && scope.row['dateRangeData'][1] | format('YYYY/MM/DD a') }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="dayNum" label="出差天数" width="100">
        <template slot-scope="scope">
          <el-input v-if="isEdit" v-model="scope.row['dayNum']" disabled type="number" size="small" placeholder="自动计算" />
          <div v-else>{{ scope.row['dayNum'] }}</div>
        </template>
      </el-table-column>
      <el-table-column :align="isEdit?'left':'right'" prop="hotelFee" label="住宿费(元)" width="120">
        <template slot-scope="scope">
          <el-input
            v-if="isEdit"
            v-model="scope.row['hotelFee']"
            :oninput="`
              if(value>999999999) {value=999999999}
              else if(value < 0) {value = null}
          ` "
            placeholder="请输入"
            type="number"
            size="small"
            @change="numberInputChange(scope.row, 'hotelFee')"
            @mousewheel.native.prevent
          />
          <!-- <ToolTip v-else :content="scope.row['hotelFee']" /> -->
          <PriceColumn v-else :real-val="scope.row['hotelFee']" :price="scope.row['hotelFee']" />
        </template>
      </el-table-column>
      <el-table-column :align="isEdit?'left':'right'" prop="carFare" label="交通费(元)" width="120">
        <template slot-scope="scope">
          <el-input
            v-if="isEdit"
            v-model="scope.row['carFare']"
            :oninput="`
              if(value>999999999) {value=999999999}
              else if(value < 0) {value = null}
          ` "
            placeholder="请输入"
            type="number"
            size="small"
            @change="numberInputChange(scope.row, 'carFare')"
            @mousewheel.native.prevent
          />
          <PriceColumn v-else :real-val="scope.row['carFare']" :price="scope.row['carFare']" />
        </template>
      </el-table-column>
      <el-table-column label="商务宴请餐次及费用" align="center">
        <el-table-column prop="breakfastsNum" width="90">
          <template slot="header" slot-scope="scope">
            <div class="dynamic-table-header">
              <span v-if="isEdit" style="color: #f56c6c;">*</span>
              <span class="label">早餐次数</span>
            </div>
          </template>
          <template slot-scope="scope">
            <el-input
              v-if="isEdit"
              :class="{ 'isError': errorCell.includes(`breakfastsNum${scope.$index}`) }"
              v-model="scope.row['breakfastsNum']"
              :oninput="`
                if(value>99) {value=99}
                else if(value < 0) {value = null}
            ` "
              placeholder="请输入"
              size="small"
              type="text"
              class="edit-table-input-text"
              clearable
              @input="valToPureNum($event, scope.row, 'breakfastsNum', scope.$index)"/>
            <ToolTip v-else :content="scope.row['breakfastsNum']" />
          </template>
        </el-table-column>
        <el-table-column prop="lunchNum" width="90">
          <template slot="header" slot-scope="scope">
            <div class="dynamic-table-header">
              <span v-if="isEdit" style="color: #f56c6c;">*</span>
              <span class="label">午餐次数</span>
            </div>
          </template>
          <template slot-scope="scope">
            <el-input
              v-if="isEdit"
              :class="{ 'isError': errorCell.includes(`lunchNum${scope.$index}`) }"
              v-model="scope.row['lunchNum']"
              :oninput="`
                if(value>99) {value=99}
                else if(value < 0) {value = null}
            ` "
              placeholder="请输入"
              size="small"
              type="text"
              class="edit-table-input-text"
              clearable
              @input="valToPureNum($event, scope.row, 'lunchNum', scope.$index)"/>
            <ToolTip v-else :content="scope.row['lunchNum']" />
          </template>
        </el-table-column>
        <el-table-column prop="dinnerNum" label="晚餐次数" width="90">
          <template slot="header" slot-scope="scope">
            <div class="dynamic-table-header">
              <span v-if="isEdit" style="color: #f56c6c;">*</span>
              <span class="label">晚餐次数</span>
            </div>
          </template>
          <template slot-scope="scope">
            <el-input
              v-if="isEdit"
              :class="{ 'isError': errorCell.includes(`dinnerNum${scope.$index}`) }"
              v-model="scope.row['dinnerNum']"
              :oninput="`
                if(value>99) {value=99}
                else if(value < 0) {value = null}
            ` "
              placeholder="请输入"
              size="small"
              type="text"
              class="edit-table-input-text"
              clearable
              @input="valToPureNum($event, scope.row, 'dinnerNum', scope.$index)"/>
            <ToolTip v-else :content="scope.row['dinnerNum']" />
          </template>
        </el-table-column>
        <el-table-column :align="isEdit?'left':'right'" prop="banquetFee" label="商务宴请费(元)" width="120">
          <template slot-scope="scope">
            <el-input
              v-if="isEdit"
              v-model="scope.row['banquetFee']"
              :oninput="`
              if(value>999999999) {value=999999999}
              else if(value < 0) {value = null}
          ` "
              placeholder="请输入"
              type="number"
              size="small"
              @change="numberInputChange(scope.row, 'banquetFee')"
              @mousewheel.native.prevent
            />
            <PriceColumn v-else :real-val="scope.row['banquetFee']" :price="scope.row['banquetFee']" />
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column :align="isEdit?'left':'right'" prop="travelAllowance" width="130">
        <template slot="header" slot-scope="scope">
          <span>出差补助(元)</span>
          <el-tooltip placement="top">
            <div slot="content">{{ travelAllowanceTip }}</div>
            <tipIcon is-diy style="margin-left: 0"/>
          </el-tooltip>
        </template>
        <template slot-scope="scope">
          <el-input v-if="isEdit" v-model="scope.row['travelAllowance']" disabled type="number" size="small" placeholder="自动计算" />
          <PriceColumn v-else :real-val="scope.row['travelAllowance']" :price="scope.row['travelAllowance']" />
        </template>
      </el-table-column>
      <el-table-column v-if="isEdit" align="left" label="操作" width="100" fixed="right">
        <template slot-scope="scope">
          <div style="padding: 0 10px;">
            <el-button :disabled="travelProjectList.length === 1" type="text" @click="handleDelete(scope.row, scope.$index)">
              <span style="font-size:14px;">删除</span>
            </el-button>
            <el-button type="text" @click="handleCopy(scope.row)">
              <span style="font-size:14px;">复制</span>
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
// components
import SectionTitle from '@/components/Title';
import ThreeLevelArea from '@/components/ThreeLevelArea';
// utils
import { showModal } from '@/utils/message';
import { format } from '@/filters/date';
import { paramsRangeFormat } from '@/utils/paramsFormat';
// img
import AmountIcon from '@/assets/chargeOffDetail/incomeAmount.png';

export default {
  components: {
    SectionTitle,
    ThreeLevelArea
  },
  filters: { format },
  model: {
    prop: 'totalReimbursementAmount',
    event: 'change'
  },
  props: {
    totalReimbursementAmount: {
      type: Number | String,
      default: null
    },
    isEdit: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      AmountIcon,
      travelProjectList: [{
        arrival: '',
        banquetFee: '',
        breakfastsNum: '',
        carFare: '',
        dayNum: null,
        departure: '',
        dinnerNum: '',
        hotelFee: '',
        lunchNum: '',
        dateRangeData: null,
        travelAllowance: null
      }],
      errorCell: []
    };
  },
  computed: {
    titleTip() {
      return '总报销金额=住宿费+交通费+商务宴请费+出差补助';
    },
    travelAllowanceTip() {
      return '出差补助 = 80×出差天数-20×早餐次数-30×午餐次数-30×晚餐次数';
    },
    rangeKeyArr() {
      return [
        { attr: 'dateRangeData', start: 'startDate', end: 'endDate', type: 'number' }
      ];
    },
    getTotalReimbursementAmount() {
      if (this.totalReimbursementAmount || this.totalReimbursementAmount === 0) {
        return this.totalReimbursementAmount;
      }
      return '--';
    }
  },
  watch: {},
  methods: {
    handleAdd() {
      this.travelProjectList.push({ });
    },
    handleCopy(rowData) {
      const copyData = _.cloneDeep(rowData);
      if (copyData.id || copyData.id === 0) delete copyData.id;
      this.travelProjectList.push(copyData);
      this.calculateTotalAmount();
    },
    handleDelete(data, index) {
      showModal('是否确定删除?').then(() => {
        this.travelProjectList.splice(index, 1);
        this.calculateTotalAmount();
      });
    },
    // 起始日期
    datePickerChange(date, index) {
      if (!date || !Array.isArray(date) || date.length < 1) {
        this.travelProjectList[index]['dayNum'] = null;
        this.calculateTravelAllowance(index);
        this.calculateTotalAmount();
        return;
      }
      const startDate = date[0]; // 开始日期
      const endDate = date[1]; // 结束日期
      const startDateIsMorning = new Date(startDate).getHours() < 12; // 是否在上午开始
      const endDateIsMorning = new Date(endDate).getHours() < 12; // 是否在上午结束
      const dayConstant = 24 * 60 * 60 * 1000; // 一天的时间戳
      const differTimestamp = endDate - startDate;
      let differDay = Math.ceil(differTimestamp / dayConstant); // 相差天数
      const differHours = new Date(endDate).getHours() - new Date(startDate).getHours();
      if ((startDateIsMorning && endDateIsMorning) || (!startDateIsMorning && !endDateIsMorning)) { // 开始结束同为上午/下午
        differDay = differHours <= 0 ? differDay + 0.5 : differDay - 0.5;
      }
      this.$set(this.travelProjectList[index], 'dayNum', differDay);
      this.calculateTravelAllowance(index);
      this.errorCell = [];
    },
    // 选择城市
    threeLevelArea(data, item, key) {
      item[key] = data.join(',');
      this.errorCell = [];
    },
    onSelectArea(data) {
      if (!data) return [];
      if (typeof data === 'string') {
        return data.split(',');
      } else {
        return data;
      }
    },
    // 保留两位小数
    numberInputChange(row, key) {
      if (row[key]) {
        const numVal = Number(row[key]);
        row[key] = numVal.toFixed(2);
      }
      this.calculateTotalAmount();
    },
    // 纯数字
    valToPureNum(text, row, key, index) {
      if (row[key]) row[key] = text.replace(/[^\d]/g, '');
      this.calculateTravelAllowance(index);
    },
    // 计算出差补助
    calculateTravelAllowance(index) {
      const data = this.travelProjectList[index] || {};
      const { dayNum, breakfastsNum, lunchNum, dinnerNum } = data;
      const breakfastsDebit = breakfastsNum ? 20 * breakfastsNum : 0;
      const lunchNumDebit = lunchNum ? 30 * lunchNum : 0;
      const dinnerNumDebit = dinnerNum ? 30 * dinnerNum : 0;
      if (!dayNum) {
        if (breakfastsDebit || lunchNumDebit || dinnerNumDebit) {
          this.$message.warning(`第${index + 1}项补助数据填写异常，请检查确认`);
        }
        this.$set(this.travelProjectList[index], 'travelAllowance', 0);
        return;
      }
      let result = dayNum * 80 - breakfastsDebit - lunchNumDebit - dinnerNumDebit;
      if (result < 0) {
        this.$message.warning(`第${index + 1}项补助数据填写异常，请检查确认`);
        result = 0;
      }
      this.$set(this.travelProjectList[index], 'travelAllowance', result);
      this.calculateTotalAmount();
    },
    // 计算总报销金额
    calculateTotalAmount() {
      this.$nextTick(() => {
        let totalAmount = 0;
        this.travelProjectList.forEach(item => {
          const { hotelFee = 0, carFare = 0, banquetFee = 0, travelAllowance = 0 } = item;
          const currAmount = (+hotelFee) + (+carFare) + (+banquetFee) + (+travelAllowance);
          totalAmount += currAmount;
        });
        this.$emit('change', totalAmount.toFixed(2));
      });
    },
    validateForm() {
      return new Promise((resolve, reject) => {
        let isOk = true;
        const errorCell = [];
        const requiredKeyList = ['departure', 'arrival', 'dateRangeData', 'breakfastsNum', 'lunchNum', 'dinnerNum'];
        this.travelProjectList.forEach((item, index) => {
          requiredKeyList.forEach(key => {
            if (!item[key]) {
              isOk = false;
              errorCell.push(`${key}${index}`);
            }
          });
        });
        this.errorCell = errorCell;
        isOk ? resolve(true) : reject(false);
      });
    },
    getTableData() {
      const tableList = _.cloneDeep(this.travelProjectList);
      tableList.forEach(item => {
        paramsRangeFormat(this.rangeKeyArr, item);
      });
      return tableList;
    },
    setTableData(list) {
      if (Array.isArray(list) && list.length) {
        list.forEach(item => {
          this.$set(item, 'dateRangeData', [item.startDate, item.endDate]);
          delete item.startDate;
          delete item.endDate;
          if (!this.isEdit) {
            item['departure'] = item['departure'].replace(/,/g, '-');
            item['arrival'] = item['arrival'].replace(/,/g, '-');
            const fixedKeys = ['hotelFee', 'carFare', 'banquetFee', 'travelAllowance'];
            fixedKeys.forEach(key => {
              if (item[key]) {
                item[key] = (+item[key]).toFixed(2);
              }
            });
          }
        });
      }
      this.travelProjectList = list;
    }
  }
};
</script>

<style lang="scss" scoped>
.common-project-container {
  &::v-deep {
    .el-table--group::after, .el-table--border::after {
      width: 0;
    }
    .el-table thead.is-group th {
      background-color: #F9F9F9 !important;
    }
    .el-table {
      border-color: transparent;
      thead {
        tr:first-child {
          th.dynamic-edit-table-cell {
            &:last-child {
              border-right-color: transparent;
            }
          }
        }
        th.el-table__cell {
          background-color: #F9F9F9 !important;
        }
      }
      .el-select {
        width: 100%;
      }
      .el-cascader--large {
        width: 100%;
      }
      .el-table__body td {
        background-color: #fff !important;
      }
      .el-cascader-menu__wrap {
        height: unset !important;
        max-height: 204px !important;
      }
      .el-select__caret {
        color: #333;
      }
      .el-table__row {
        td {
          padding: 0;
          height: 56px;
        }
        .cell {
          padding: 0;
          .el-input__inner {
            border-radius: 0;
            width: 100%;
            height: 56px;
            text-overflow: ellipsis;
            padding-right: 30px;
            border-color: transparent;
          }
        }
      }
      .el-date-editor .el-range-separator {
        width: 24px;
        display: flex;
        align-items: center;
      }
      .is-scrolling-none {
        .el-table__empty-block {
          width: 100% !important;
        }
      }
      .el-table__empty-text {
        width: 100%;
      }
      tbody {
        tr {
          td:last-child {
            border-right-color: transparent;
          }
        }
        .el-table__row {
          &:last-child {
            td {
              border-bottom: 1px solid #EBEEF5;
            }
          }
        }
      }
    }
  }
  .isError {
    &::v-deep {
      .el-input__inner {
        border-color: red !important;
      }
      .attachment-container {
        border:1px solid red;
      }
    }
  }
  .total-amount-price {
    display: flex;
    align-items: center;
    background-color: #f8f8f8;
    color: #999;
    font-size: 14px;
    font-weight: normal;
    margin-left: 10px;
    padding: 4px 6px;
    border-radius: 4px;
    > img {
      width: 14px;
      margin-right: 5px;
    }
    .price {
      font-size: 14px;
      color: #406eff;
      font-weight: bold;
    }
  }
  .options-btn-group {
    position: absolute;
    right: 0;
    display: flex;
    align-items: center;
  }
}
.only-view-mode {
  &::v-deep {
    .el-table__row {
      td {
        padding: 0 8px !important;
      }
    }
  }
}
</style>
